<template>
  <div class="xtx-city" ref="target">
    <!-- 配送地址框 -->
    <div class="select" @click="toggle" :class="{ active: visible }">
      <span v-if="!fullLocation" class="placeholder">{{ placeholder }}</span>
      <span v-else class="value">{{ fullLocation }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <!-- 地区弹出层 -->
    <div class="option" v-if="visible">
      <!-- 加载动画 -->
      <div class="loading" v-if="loading"></div>
      <!-- 地区展示 -->
      <template v-else>
        <span
          class="ellipsis"
          @click="changeItem(item)"
          v-for="item in corrList"
          :key="item.id"
          >{{ item.name }}</span
        >
      </template>
    </div>
  </div>
</template>

<script>
import { computed, onUnmounted, reactive, ref } from 'vue'
import { onClickOutside } from '@vueuse/core'
import axios from 'axios'

// 获取省市区的函数
const getCityData = () => {
  /*
    数据：https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json
    1.本地没缓存 发请求拿数据
    2.本地有缓存，取出本地数据
    返回一个promise 在then中取数据 理由：这里可能是异步操作，也可能是同步操作
  */

  return new Promise((resolve, reject) => {
    // 约定：存储在window的CtiyData字段
    if (window.cityData) {
      resolve(window.cityData)
    } else {
      axios({
        url: 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
      }).then(({ data }) => {
        window.cityData = data
        resolve(data)
      })
    }
  })
}

export default {
  name: 'XtxCity',
  props: {
    fullLocation: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择配送区域'
    }
  },
  setup (props, { emit }) {
    const visible = ref(false) // 控制弹层的显示与隐藏

    const allCityData = ref([]) // 所有省市区数据

    const loading = ref(false) // 是否正在加载数据

    let timer = '' // 为了看见加载效果

    // 打开、关闭的方法
    const open = () => {
      visible.value = true
      loading.value = true
      getCityData().then((data) => {
        allCityData.value = data
      })

      // 清空之前选择城市信息 不然弹层会显示旧的数据
      for (const k in changeResult) {
        changeResult[k] = ''
      }

      // 延时器器只是为了看见加载效果
      timer = setTimeout(() => {
        loading.value = false
      }, 1000)
    }
    // open()

    const close = () => {
      visible.value = false
    }

    // 为 select提供切换的按钮
    const toggle = () => {
      visible.value ? close() : open()
    }

    // 实现点击组件外部，关闭弹出框 @vueuse/core onClickOutside(监听的元素，处理函数)
    const target = ref(null)
    onClickOutside(target, () => {
      close()
    })

    // 通过计算属性，实现当前显示的地区数组
    const corrList = computed(() => {
      // 省级地区数组
      let list = allCityData.value

      // 根据省级code，获取市信息
      if (changeResult.provinceCode && changeResult.provinceName) {
        list = list.find((p) => p.code === changeResult.provinceCode).areaList
      }

      // 根据市级code，获取其下的区信息
      if (changeResult.cityCode && changeResult.cityName) {
        list = list.find((c) => c.code === changeResult.cityCode).areaList
      }

      return list
    })

    // 定义选择的省市区
    const changeResult = reactive({
      // 省
      provinceCode: '',
      provinceName: '',
      // 市
      cityCode: '',
      cityName: '',
      // 区
      countyCode: '',
      countyName: '',
      // 合并
      fullLocation: ''
    })

    // 当点击地区按钮后记录
    const changeItem = (item) => {
      if (item.level === 0) {
        // 省
        changeResult.provinceCode = item.code
        changeResult.provinceName = item.name
      }
      if (item.level === 1) {
        // 市
        changeResult.cityCode = item.code
        changeResult.cityName = item.name
      }
      if (item.level === 2) {
        // 区
        changeResult.countyCode = item.code
        changeResult.countyName = item.name
        // 设置完整地区信息
        changeResult.fullLocation = `${changeResult.provinceName} ${changeResult.cityName} ${changeResult.countyName}`
        // 这是最后一级 选择完毕 关闭弹窗 通知父组件
        close()
        emit('change', changeResult)
      }
    }

    onUnmounted(() => {
      clearTimeout(timer)
    })

    return { visible, toggle, target, loading, corrList, changeItem }
  }
}
</script>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    .loading {
      height: 290px;
      width: 100%;
      background: url(../../assets/images/loading.gif) no-repeat center;
    }
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
